package com.huanglejing.shanggou.fragment

import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.util.ArrayMap
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.TextView
import com.huanglejing.mylibrary.KLog
import com.huanglejing.shanggou.R
import com.huanglejing.shanggou.bean.NowOrderBean
import com.huanglejing.shanggou.common.AppBaseFragment
import com.huanglejing.shanggou.common.AppContext
import com.huanglejing.shanggou.adapter.MineOrderAdapter
import com.huanglejing.shanggou.data.CacheCustomerId
import com.huanglejing.shanggou.interfaces.MineOrderContract.MineOrderPresenter
import com.huanglejing.shanggou.interfaces.MineOrderContract.MineOrderView
import com.huanglejing.shanggou.interfaces.ProductImgsContract
import com.huanglejing.shanggou.presenterimpl.MineOrderImpl
import com.huanglejing.shanggou.rx.SimpleSubscriber
import com.huanglejing.shanggou.rx.event.CompanyIdEvent
import com.huanglejing.shanggou.rx.rxbus.RxBus
import com.huanglejing.shanggou.utils.addTo
import com.jcodecraeer.xrecyclerview.ProgressStyle
import com.jcodecraeer.xrecyclerview.XRecyclerView
import kotlinx.android.synthetic.main.fragment_mine_order.*
import rx.Observable

/**
 * Created by Administrator on 2016/8/5 0005.
 */
class MineOrderFragment : AppBaseFragment<MineOrderPresenter<MineOrderView>, MineOrderView>(), MineOrderView, XRecyclerView.LoadingListener {
    private var mTitles: List<String>? = null
    var mData = arrayListOf<NowOrderBean>()
    var nowPage = 0
    var orderStatus = "0"
    var companyId = ""
    var myAdapter: MineOrderAdapter? = null
    private val mEmptyView by lazy {
        rootViewWeakRef?.get()?.findViewById<View>(R.id.ll_xr_empty)
    }
    private val mErrorView by lazy {
        rootViewWeakRef?.get()?.findViewById<View>(R.id.ll_xr_error)
    }
    protected val mTabLayout: TabLayout by lazy { tabLayout }

    init {
        containerId = R.id.fl_head_container
    }
    override var isShowLoading: Boolean =false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mTitles = listOf(resources.getString(R.string.str_all), resources.getString(R.string.str_processing), resources.getString(R.string.str_complete))
        RxBus.get().toObservable(CompanyIdEvent::class.java)
                .doOnNext {
                    companyId = it?.companyId?:""
                    mBasePresenter?.getNowOrder()
                }.subscribe(SimpleSubscriber()).addTo(rxManager)
    }

    override fun getRequestParams(): Observable<Map<String, Any>> {
        val map = ArrayMap<String, String>().apply {
            put("customerId", CacheCustomerId ?: "")
            put("companyId", companyId)
            put("orderStatus", orderStatus)
            put("offset", nowPage?.times(50)?.toString())
        }
        return Observable.just(map)
    }


    override fun createPresenter(): Any? = MineOrderImpl()

    override fun getLayoutId(): Int = R.layout.fragment_mine_order

    override fun initWidget(rootView: View?) {
        mTabLayout.setBackgroundColor(AppContext.get().resources.getColor(R.color.white))
        mTitles?.forEach { mTabLayout.addTab(tabLayout.newTab().setText(it)) }

        mTabLayout?.setOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabSelected(tab: TabLayout.Tab?) {
                if (0 == tab?.position) {
                    orderStatus = "0"
                    nowPage = 0

                } else if (1 == tab?.position) {
                    orderStatus = "1"
                    nowPage = 0
                } else if (2 == tab?.position) {
                    orderStatus = "2"
                    nowPage = 0
                }
                mBasePresenter?.getNowOrder()
                //  mAdapter?.setNewData(mData)
            }
        })


        xr_mine_order_list?.setLoadingListener(this@MineOrderFragment)
        xr_mine_order_list?.setLoadingMoreProgressStyle(ProgressStyle.BallRotate)
        xr_mine_order_list?.setRefreshProgressStyle(ProgressStyle.BallRotate)

        val layoutManager = LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        xr_mine_order_list?.setLayoutManager(layoutManager);

        myAdapter = MineOrderAdapter(getActivity(), mData)
        xr_mine_order_list?.adapter = myAdapter
    }


    override fun onResume() {
        super.onResume()
      //  isShow = true
        setIvExitVisible(false)
        setIvExitVisible(false)
        setIvExitShow()
        if (getActivity()?.findViewById<ViewPager>(R.id.main_container)?.currentItem == 3) {
            getActivity()?.findViewById<TextView>(R.id.tv_title)?.setText(resources.getString(R.string.str_order))
            getActivity()?.findViewById<TextView>(R.id.tv_login_language)?.visibility = View.GONE
        }

    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        if (isVisibleToUser) {
            setIvExitVisible(false)
            getActivity()?.findViewById<TextView>(R.id.tv_title)?.setText(resources.getString(R.string.str_order))
        }else{
        }
        super.setUserVisibleHint(isVisibleToUser)
        isShowLoading=isVisibleToUser
    }

    override fun initData() {
    }

    override fun <T> showContent(data: T?) {
        try {
            val mNetData = data as? ArrayList<NowOrderBean>
            if (mNetData != null) {
                if (nowPage > 0) {
                    mData?.addAll(mNetData)
                } else {
                    mData?.clear()
                    mData?.addAll(mNetData)
                }
                if (mData?.size?:0<1 && mErrorView!=null){
                    xr_mine_order_list?.emptyView=mEmptyView
                }
                myAdapter?.setData(mData ?: arrayListOf())
                myAdapter?.notifyDataSetChanged()
                loadComPlete(mNetData?.size)
            }
        } catch (e: Exception) {
            KLog.e(e?.message)
        }

    }

    fun loadComPlete(currentDataSize: Int) {

        xr_mine_order_list?.loadMoreComplete()
        xr_mine_order_list?.refreshComplete()
        if (currentDataSize < 50) {
            xr_mine_order_list?.setNoMore(true)
        } else {
            xr_mine_order_list?.setNoMore(false)
        }

    }

    override fun showError(e: Throwable?) {
        KLog.e(e?.message)
        mData?.clear()
        if (mErrorView!=null){
            xr_mine_order_list?.emptyView=mErrorView
            mErrorView?.setOnClickListener {
                mBasePresenter?.getNowOrder()
            }
        }

        myAdapter?.setData(arrayListOf())
        loadComPlete(50)
    }

    companion object {
        @JvmStatic
        fun newInstance(): MineOrderFragment {
            return MineOrderFragment()
        }
    }

    override fun onRefresh() {
        nowPage = 0;
        mBasePresenter?.getNowOrder()
    }

    override fun onLoadMore() {
        nowPage++;
        mBasePresenter?.getNowOrder()
    }
}